﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UFrame.LoopScrollView;
using System.Linq;
using UFrame;

#if UNITY_STANDALONE_OSX
using WindowsTool = OsxWindowsTool;
#endif

namespace GView
{
    public partial class MainPanel : MainPanelInternal
    {
        protected UFrame.BridgeUI.Common.ListViewer ActiveFileListContent
        {
            get
            {
                if (listOrGridTog.isOn)
                {
                    return FileListContent2;
                }
                return FileListContent;
            }
        }


        protected override void OnInitialize()
        {
            base.OnInitialize();
            m_routeList = new List<Route>();
            m_routerSet = new HashSet<string>();
            m_selectedPacketList = new List<Route>();
            m_assetPathDic = new Dictionary<string, string>();
            ConnectMysqlDB();
            CreateLeftOptions();
            InitView();
            LoadMetaFiles();
        }

        protected override void OnSettingBtnClick()
        {
            base.OnSettingBtnClick();
            m_lastLayerNameStr = layerNameInput.text = ToLayerNamesEditString();
            if (m_sourceFolders == null)
                m_sourceFolders = new string[] { };
            m_lastSourcePathStr = importPathInput.text = string.Join("|", m_sourceFolders);
        }

        protected override void OnsettingApplayBtnClick()
        {
            base.OnsettingApplayBtnClick();
            SettingPanel.gameObject.SetActive(false);

            if (m_lastLayerNameStr != layerNameInput.text)
            {
                RecordLayerNameToDB(layerNameInput.text);
            }

            if (!string.IsNullOrEmpty(importPathInput.text))
            {
                if (m_lastSourcePathStr != importPathInput.text)
                {
                    m_sourceFolders = importPathInput.text.Split('|');
                    if (m_sourceFolders.Length > 0)
                    {
                        for (int i = 0; i < m_sourceFolders.Length; i++)
                        {
                            DBManager.Instance.SetSourceFolder(i, m_sourceFolders[i]);
                        }
                        RefreshMetaFiles();
                    }
                }
            }
        }

        protected override void OnsizeViewSliderChanged(float arg0)
        {
            base.OnsizeViewSliderChanged(arg0);
            SetFileListContentSize(arg0, true);
        }

        protected override void OnopenFolderClick()
        {
            base.OnopenFolderClick();
            if (m_activePacket != null && m_assetPathDic.TryGetValue(m_activePacket.guid, out string folderPath))
            {
                WindowsTool.OpenSelectFolder(folderPath);
            }
        }

        protected override void OnexportBtnClick()
        {
            base.OnexportBtnClick();
            if (m_activePacket != null && m_assetPathDic.TryGetValue(m_activePacket.guid, out string folderPath))
            {
                var folder = WindowsTool.OpenFileFolderPath("请选择文件夹");
                if (!string.IsNullOrEmpty(folder))
                {
                    WindowsTool.CopyDir(folderPath, folder);
                    var folderName = System.IO.Path.GetFileName(folderPath);
                    WindowsTool.OpenSelectFolder(folder + "\\" + folderName);
                    Debug.LogWarning(folder + "\\" + folderName);
                }
            }
        }

        protected override void OnfilePathApplyBtnClick()
        {
            base.OnfilePathApplyBtnClick();
            if (m_activePacket == null || string.IsNullOrEmpty(m_activePacket.guid))
            {
                Debug.LogError("packet empty!");
                return;
            }
            var dirPath = filePathInputField.text;
            if (!string.IsNullOrEmpty(dirPath))
            {
                if (System.IO.Directory.Exists(dirPath))
                {
                    var guidLast = System.IO.Directory.GetFiles(dirPath, "*.geta");
                    if (guidLast == null || guidLast.Length == 0)
                    {
                        CreateMetaFile(dirPath, m_activePacket.guid);
                        OnResItemSelect(m_activePacket);
                    }
                    else if (m_activePacket.guid != System.IO.Path.GetFileNameWithoutExtension(guidLast[0]))
                    {
                        ShowState("文件夹已经包含*.geta，可能被占用！", Color.red);
                    }
                }
            }
        }

        protected override void OnSearchInputEndEdit(string arg0)
        {
            base.OnSearchInputEndEdit(arg0);
            if (string.IsNullOrEmpty(arg0))
            {
                RefreshResList();
            }
        }

        protected override void OnNameInputEndEdit(string arg0)
        {
            if (m_activePacket != null)
            {
                m_activePacket.name = arg0;
                var changed = DBManager.Instance.ChangeRouteName(m_activePacket.guid, arg0);
                ShowState("name changed" + (changed ? "ok" : "failed"), changed ? Color.green : Color.red);
            }
        }

        protected override void OnDescInputEndEdit(string arg0)
        {
            if (m_activePacket != null)
            {
                m_activePacket.description = arg0;
                var changed = DBManager.Instance.ChangeRouteDesc(m_activePacket.guid, arg0);
                ShowState("desc changed" + (changed ? "ok" : "failed"), changed ? Color.green : Color.red);
            }
        }

        protected override void OnTagsInputEnd(string arg0)
        {
            if (m_activePacket != null)
            {
                m_activePacket.flag = arg0;
                var changed = DBManager.Instance.ChangeFlags(m_activePacket.guid, arg0);
                ShowState("flags changed" + (changed ? "ok" : "failed"), changed ? Color.green : Color.red);
            }
        }

        protected override void OnImportIcon()
        {
            var filePath = WindowsTool.OpenFilePath("选择图标文件", "png");
            if (!string.IsNullOrEmpty(filePath))
            {
                ShowState("loading short cart:" + filePath, Color.green);
                var bytes = System.IO.File.ReadAllBytes(filePath);
                if (bytes != null && bytes.Length > 0)
                {
                    var texture = new Texture2D(0, 0);
                    texture.LoadImage(bytes);
                    if (texture && m_activePacket != null)
                    {
                        SetAsIcon(texture);
                    }
                    else
                    {
                        ShowState("texture error", Color.red);
                    }
                }
            }
        }

        protected override void OnCreateClick()
        {
            Route route = new Route();
            route.source = ResLayerName.IDToMask(binding.TypeList.currentID);
            var inserted = DBManager.Instance.InsertRoute(route);
            if (inserted)
            {
                AddRouteToList(route);
                RefreshResList();
            }
            else
            {
                ShowState("插入失败！", Color.red);
            }
        }

        protected override void OnSearchBtnClick()
        {
            base.OnSearchBtnClick();
            RefreshResList();
        }

        protected override void OnImportBtnClick()
        {
            var folderPath = WindowsTool.OpenFileFolderPath("选择导入的文件夹");
            if (!string.IsNullOrEmpty(folderPath))
            {
                bool changed = false;
                if (ImportMode.value == 0)
                {
                    if (DeepTog.isOn)
                    {
                        changed |= ImportFolderDeep(folderPath);
                    }
                    else
                    {
                        var index = System.IO.Path.GetDirectoryName(folderPath).Length + 1;
                        var routerName = folderPath.Substring(index);
                        ImportFolderAsRoute(folderPath, routerName);
                    }
                }
                else if (ImportMode.value == 1)
                {
                    var dirs = System.IO.Directory.GetDirectories(folderPath);
                    foreach (var subFolder in dirs)
                    {
                        if (DeepTog.isOn)
                        {
                            changed |= ImportFolderDeep(subFolder);
                        }
                        else
                        {
                            var index = System.IO.Path.GetDirectoryName(subFolder).Length + 1;
                            var routerName = subFolder.Substring(index);
                            ImportFolderAsRoute(subFolder, routerName);
                        }
                    }
                }
                if (changed)
                {
                    RefreshResList();
                }
            }
        }

        protected override void OndeleteBtnClick()
        {
            base.OndeleteBtnClick();
            if (m_activePacket != null)
            {
                var deleted = DBManager.Instance.DeleteRoute(m_activePacket.guid);
                if (deleted)
                {
                    var id = m_selectedPacketList.IndexOf(m_activePacket);
                    m_selectedPacketList.RemoveAt(id);
                    DeleteGetaFileByGuid(m_activePacket.guid);
                    m_routeList.Remove(m_activePacket);

                    if (m_selectedPacketList.Count > 0)
                        m_activePacket = m_selectedPacketList[Mathf.Max(id - 1, 0)];
                    RefreshResList();
                }
            }
        }

        protected void DeleteGetaFileByGuid(string guid)
        {
            if (m_assetPathDic.TryGetValue(guid, out var assetPath))
            {
                try
                {
                    var guidFilePath = System.IO.Path.Combine(assetPath, string.Format("{0}.geta", guid));
                    if (System.IO.File.Exists(guidFilePath))
                    {
                        System.IO.File.Delete(guidFilePath);
                        ShowState("delete guid file:" + guidFilePath, Color.yellow);
                    }
                    m_assetPathDic.Remove(guid);
                }
                catch (System.Exception e)
                {
                    ShowState("delete guid file error:" + e.Message, Color.red);
                    Debug.LogException(e);
                }
            }
        }

        protected override void OnApplyClick()
        {
            if (m_activePacket != null)
            {
                UpdateMetaText(m_activePacket.guid);
                OnResItemSelect(m_activePacket);
            }
        }

        protected override void OnEditInfoClick()
        {
            ShowEditPanel();
            if (m_activePacket != null)
            {
                TypeInfoText.text = LayerToNames(m_activePacket.source);
                SourceListSelector.options = ResLayerName.layerNames;
                for (int i = 0; i < ResLayerName.MAX_LAYER_COUNT; i++)
                {
                    if (ResLayerName.MaskContains(m_activePacket.source, i))
                    {
                        SourceListSelector.SetSelect(i, false);
                    }
                }
                SourceListSelector.onSelectIDs.RemoveAllListeners();
                SourceListSelector.onSelectIDs.AddListener(OnSelectLayerIds);
            }
        }

        protected override void OnRefreshBtnClick()
        {
            base.OnRefreshBtnClick();
            RefreshMetaFiles();
            RefreshResList();
        }

        protected float m_lastClickClear;

        protected override void OnClearEmptyBtnClick()
        {
            if (Time.time - m_lastClickClear > 0.5f)
            {
                m_lastClickClear = Time.time;
                ShowState("双击以清理！", Color.red);
                return;
            }

            List<Route> clearAble = new List<Route>();
            for (int i = 0; i < m_routeList.Count; i++)
            {
                var route = m_routeList[i];
                if (string.IsNullOrEmpty(route.description) &&
                    !m_assetPathDic.ContainsKey(route.guid))
                {
                    clearAble.Add(route);
                }
            }
            for (int i = 0; i < clearAble.Count; i++)
            {
                var route = clearAble[i];
                DBManager.Instance.DeleteRoute(route.guid);
                m_routeList.Remove(route);
            }
            RefreshResList();
        }
        protected override void OnlistOrGridTogChanged(bool arg0)
        {
            FileListContent.gameObject.SetActive(!arg0);
            FileListContent2.gameObject.SetActive(arg0);
            DetailScrollView.content = ActiveFileListContent.transform as RectTransform;

            if (m_activePacket != null)
            {
                OnResItemSelect(m_activePacket);
            }
        }
    }

    public partial class MainPanel
    {
        protected List<Route> m_routeList;
        protected LoopListView m_packetLoopList;
        protected List<Route> m_selectedPacketList;
        protected Route m_activePacket;
        protected string[] m_importRule = new string[] { "单个", "一组" };
        protected Dictionary<string, string> m_assetPathDic;
        protected string[] m_sourceFolders;
        protected string m_lastLayerNameStr;
        protected string m_lastSourcePathStr;
        protected HashSet<string> m_routerSet;

        protected void InitView()
        {
            if (SettingManager.Instance.TryGetInt(SettingID.MAIN_PANEL_GRIDE_SIZE, out int size) && size > 0)
            {
                sizeViewSlider.value = size;
            }
            else
            {
                OnsizeViewSliderChanged(sizeViewSlider.value);
            }
            RefreshResList();
            ShowOptionDropDown();
            OnlistOrGridTogChanged(listOrGridTog.isOn);
        }

        protected void ConnectMysqlDB()
        {
            var sourcePath = System.Environment.CurrentDirectory + "/" + "source.db";
            if (System.Environment.GetCommandLineArgs().Length > 1)
            {
                sourcePath = System.Environment.GetCommandLineArgs()[1];
                Debug.LogWarning("connect to:" + sourcePath);
            }
            var connected = DBManager.Instance.Connect(sourcePath);
            StateText.text = "数据库连接" + (connected ? "成功！" : "失败！");
            if (connected)
            {
                ReloadLoadRoutes();
            }
            if (connected)
            {
                LoadLayerNames();
            }
        }

        protected void LoadMetaFiles()
        {
            m_sourceFolders = DBManager.Instance.SelectFolders();
            RefreshMetaFiles();
        }

        protected System.Threading.Thread loadingThread;
        protected string loadingInfo;
        protected int totalCount;
        protected int loadingCount;
        protected int currentTotalCount;

        protected void RefreshMetaFiles()
        {
            m_assetPathDic.Clear();
            if (m_sourceFolders != null && m_sourceFolders.Length > 0)
            {
                var task = new UFrame.Task.ConditionalTask();
                task.condition = OnMetalFileLoadCondition;
                task.onUpdateAction = OnMetaFilesLoadTaskUpdate;
                task.onStartAction = OnMetaFilesLoadStart;
                task.onCompleteAction = OnMetaFilesLoadFinish;
                TaskManager.Instance.AddTask<UFrame.Task.ConditionalTask>(task);

                loadingThread = new System.Threading.Thread((x) =>
                {
                    foreach (var folder in m_sourceFolders)
                    {
                        FindMetaSourceFromFolder(folder);
                    }
                });
                loadingThread.Start();
            }
            else
            {
                binding.LoadingPanel.gameObject.SetActive(false);
            }
        }

        private bool OnMetalFileLoadCondition(UFrame.Task.ConditionalTask obj)
        {
            if (loadingThread != null && loadingThread.IsAlive)
            {
                return false;
            }
            return true;
        }

        private void OnMetaFilesLoadStart(UFrame.Task.ConditionalTask obj)
        {
            //Debug.LogError("OnMetaFilesLoadStart");
            if (loadingThread != null && loadingThread.IsAlive)
            {
                LoadingPanel.SetActive(true);
            }
        }


        private void OnMetaFilesLoadFinish(UFrame.Task.ConditionalTask obj)
        {
            //Debug.LogError("OnMetaFilesLoadFinish");
            LoadingPanel.SetActive(false);
            RefreshResList();
        }


        private void OnMetaFilesLoadTaskUpdate(UFrame.Task.ConditionalTask obj)
        {
            if (loadingThread != null && loadingThread.IsAlive)
            {
                LoadingDetail.text = loadingInfo + "\n" + string.Format("total: ({0})", totalCount);
                if (currentTotalCount > 0)
                    ProgressSlider.value = loadingCount / (float)currentTotalCount;
            }
        }

        protected void FindMetaSourceFromFolder(string folder)
        {
            if (!System.IO.Directory.Exists(folder))
                return;
            loadingInfo = "Enter:" + folder;
            var directorys = System.IO.Directory.GetDirectories(folder);
            if (directorys.Length > 0)
            {
                currentTotalCount = directorys.Length;
                loadingCount = 0;
                for (int i = 0; i < directorys.Length; i++)
                {
                    loadingCount++;
                    FindMetaSourceFromFolder(directorys[i]);
                }
            }
            var files = System.IO.Directory.GetFiles(folder, "*.geta", System.IO.SearchOption.TopDirectoryOnly);
            if (files != null)
            {
                foreach (var filePath in files)
                {
                    totalCount += 1;
                    loadingInfo = "loading:" + filePath;
                    var guid = System.IO.Path.GetFileNameWithoutExtension(filePath);
                    m_assetPathDic[guid] = System.IO.Path.GetDirectoryName(filePath);
                    Debug.LogWarning("find geta file:" + filePath);
                    if (!m_routerSet.Contains(guid))
                    {
                        ImportARouteFromPath(filePath);
                    }
                }
            }
        }

        protected void ReloadLoadRoutes()
        {
            var routes = DBManager.Instance.SelectAllRoute();
            foreach (var item in routes)
            {
                AddRouteToList(item);
            }
        }

        protected void LoadLayerNames()
        {
            var layerNames = DBManager.Instance.SelectLayers();
            if (layerNames != null)
            {
                foreach (var pair in layerNames)
                {
                    ResLayerName.ChangeLayerName(pair.Key, pair.Value);
                }
            }
        }

        protected string ToLayerNamesEditString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < ResLayerName.layerNames.Length; i++)
            {
                sb.Append(ResLayerName.layerNames[i]);
                if (i != ResLayerName.MAX_LAYER_COUNT - 1)
                    sb.Append("|");
            }
            return sb.ToString();
        }

        protected void RecordLayerNameToDB(string layerNameText)
        {
            var dic = new Dictionary<int, string>();
            var layerNames = layerNameText.Split('|');
            bool changed = false;
            for (int i = 0; i < layerNames.Length; i++)
            {
                var layername = layerNames[i];
                if (!string.IsNullOrEmpty(layername))
                {
                    if (DBManager.Instance.UpdateLayerName(i, layername))
                    {
                        ResLayerName.ChangeLayerName(i, layername);
                        changed = true;
                    }
                }
            }
            if (changed)
            {
                CreateLeftOptions();
            }
        }

        protected void ShowOptionDropDown()
        {
            ImportMode.options.Clear();
            var options = new List<UnityEngine.UI.Dropdown.OptionData>();
            for (int i = 0; i < m_importRule.Length; i++)
            {
                options.Add(new UnityEngine.UI.Dropdown.OptionData(m_importRule[i]));
            }
            ImportMode.options = options;
        }

        protected void SetFileListContentSize(float arg0, bool record = true)
        {
            FileListContent.GetComponent<GridLayoutGroup>().cellSize = Vector2.one * arg0;
            if (record)
            {
                SettingManager.Instance.SetInt(SettingID.MAIN_PANEL_GRIDE_SIZE, (int)arg0);
            }
        }

        protected void SetAsIcon(Texture2D texture)
        {
            var bytes = texture.EncodeToPNG();
            bytes = LoadShortCart(bytes);
            texture = new Texture2D(0, 0);
            if (texture.LoadImage(bytes))
            {
                m_activePacket.icon = texture;
                DBManager.Instance.ChangeRouteIcons(m_activePacket, texture);
                UpdateMetaText(m_activePacket.guid);
                RefreshResList();
            }
        }

        protected bool ImportFolderDeep(string subDir, int index = -1)
        {
            bool changed = false;
            if (index <= 0)
            {
                index = System.IO.Path.GetDirectoryName(subDir).Length + 1;
            }
            if (index < subDir.Length)
            {
                var routerName = subDir.Substring(index).Replace("\\", "-").Replace("/", "-");
                changed |= ImportFolderAsRoute(subDir, routerName);
            }
            var dirs = System.IO.Directory.GetDirectories(subDir);
            if (dirs != null)
            {
                for (int i = 0; i < dirs.Length; i++)
                {
                    changed |= ImportFolderDeep(dirs[i], index);
                }
            }
            return changed;
        }

        //��ָ��·������һ��Route
        protected bool ImportARouteFromPath(string guidPath)
        {
            Route loadedRoute = null;
            var routeText = System.IO.File.ReadAllText(guidPath);
            //���Լ���һ����Ч��route
            if (!string.IsNullOrEmpty(routeText) && loadedRoute == null)
            {
                try
                {
                    loadedRoute = JsonUtility.FromJson<Route>(routeText);
                    if (loadedRoute != null && !string.IsNullOrEmpty(loadedRoute.textureBase64))
                    {
                        loadedRoute.icon = DBController.StringToTexture(loadedRoute.textureBase64);
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogException(e);
                }
            }
            if (loadedRoute != null)
            {
                var result = DBManager.Instance.InsertRoute(loadedRoute);
                if (result)
                {
                    m_assetPathDic[loadedRoute.guid] = System.IO.Path.GetDirectoryName(guidPath);
                    AddRouteToList(loadedRoute);
                }
                return true;
            }
            return false;
        }

        protected bool ImportFolderAsRoute(string directory, string routerName)
        {
            Route loadedRoute = null;
            var files = System.IO.Directory.GetFiles(directory);
            if (files == null || files.Length <= 0)
                return false;
            var getaFiles = files.Where(x => x.EndsWith(".geta")).ToArray();
            if (getaFiles != null && getaFiles.Length > 0)
            {
                foreach (var getaItem in getaFiles)
                {
                    var guid = System.IO.Path.GetFileNameWithoutExtension(getaItem);
                    var item = m_routeList.Find(x => x.guid == guid);
                    if (item == null)
                    {
                        var routeText = System.IO.File.ReadAllText(getaItem);
                        //尝试加载一个有效的route
                        if (!string.IsNullOrEmpty(routeText) && loadedRoute == null)
                        {
                            try
                            {
                                loadedRoute = JsonUtility.FromJson<Route>(routeText);
                                if (loadedRoute != null && loadedRoute.guid == guid)
                                {
                                    if (!string.IsNullOrEmpty(loadedRoute.textureBase64))
                                        loadedRoute.icon = DBController.StringToTexture(loadedRoute.textureBase64);
                                    continue;
                                }
                            }
                            catch (System.Exception e)
                            {
                                Debug.LogException(e);
                            }
                        }
                        System.IO.File.Delete(getaItem);
                    }
                    else
                    {
                        var source = item.source | ResLayerName.IDToMask(binding.TypeList.currentID);
                        if (source != item.source)
                        {
                            item.source = source;
                            DBManager.Instance.ChangeSource(item.guid, source);
                            return true;
                        }
                        return false;
                    }
                }
            }

            if (loadedRoute != null)
            {
                var result = DBManager.Instance.InsertRoute(loadedRoute);
                if (result)
                {
                    m_assetPathDic[loadedRoute.guid] = directory;
                    AddRouteToList(loadedRoute);
                    RefreshResList();
                }
                ShowState("添加状态:" + (result ? "成功" : "失败"), Color.yellow);
                return result;
            }

            var index = directory.Replace("\\", "/").LastIndexOf('/');
            if (index >= 0)
            {
                var guid = DBManager.Instance.GetNextGUID();
                Route route = new Route();
                route.guid = guid;
                route.name = routerName;
                route.source = ResLayerName.IDToMask(binding.TypeList.currentID);
                var result = DBManager.Instance.InsertRoute(route);
                if (result)
                {
                    AddRouteToList(route);
                    CreateMetaFile(directory, guid);
                    RefreshResList();
                }
                ShowState("添加状态:" + (result ? "成功" : "失败"), Color.yellow);
                return result;
            }
            return false;
        }

        protected void CreateMetaFile(string directory, string guid)
        {
            var metaFilePath = System.IO.Path.Combine(directory, guid + ".geta");
            m_assetPathDic[guid] = directory;
            UpdateMetaText(guid);
        }

        protected void UpdateMetaText(string guid)
        {
            Route route = m_routeList.Where(x => x.guid == guid).FirstOrDefault();
            if (route != null && m_assetPathDic.TryGetValue(guid, out var directory))
            {
                var metaFilePath = System.IO.Path.Combine(directory, guid + ".geta");
                System.IO.File.WriteAllText(metaFilePath, JsonUtility.ToJson(route));
            }
        }

        protected void CreateLeftOptions()
        {
            binding.TypeList.options = ResLayerName.layerNames;
            binding.TypeList.onSelectID.AddListener(OnSelectResLayerId);
        }

        protected void OnSelectResLayerId(int id)
        {
            StateText.text = "设置选中+" + id;
            m_activePacket = null;
            RefreshResList();
        }

        protected void AddRouteToList(Route route)
        {
            if (!m_routeList.Contains(route))
            {
                m_routeList.Add(route);
            }
            m_routerSet.Add(route.guid);
        }

        protected void ShowState(string text, Color color)
        {
            binding.StateText.text = text;
            binding.StateText.color = color;
        }

        private void RefreshResList()
        {
            if (!m_packetLoopList)
            {
                m_packetLoopList = binding.ResListContent.GetComponent<UFrame.LoopScrollView.LoopListView>();
                m_packetLoopList.InitListView(0, OnGetPacketListItem);
            }
            m_selectedPacketList.Clear();
            m_routerSet.Clear();
            var layer = ResLayerName.IDToMask(binding.TypeList.currentID);
            for (int i = 0; i < m_routeList.Count; i++)
            {
                var routeItem = m_routeList[i];
                m_routerSet.Add(routeItem.guid);
                if (layer != 0 && (routeItem.source & layer) == 0)
                    continue;
                if (!string.IsNullOrEmpty(SearchInput.text) &&
                    !(routeItem.name + routeItem.flag).ToLower().Contains(SearchInput.text.ToLower()))
                    continue;
                m_selectedPacketList.Add(routeItem);
            }
            if (m_selectedPacketList.Count > 0)
            {
                m_selectedPacketList.Sort((x, y) => string.Compare(x.guid, y.guid));
                if (m_activePacket == null || string.IsNullOrEmpty(m_activePacket.guid))
                {
                    m_activePacket = m_selectedPacketList[0];
                }
                m_packetLoopList.SetListItemCount(m_selectedPacketList.Count, false);
            }
            else
            {
                m_packetLoopList.SetListItemCount(0, true);
            }
            m_packetLoopList.RefreshAllShownItem();
            searchNumText.text = m_selectedPacketList.Count.ToString();
            RightGroup.interactable = m_selectedPacketList.Count > 0;
        }

        private LoopListViewItem OnGetPacketListItem(LoopListView listView, int index)
        {
            if (m_selectedPacketList.Count <= index)
                return null;
            var route = m_selectedPacketList[index];
            LoopListViewItem item = listView.NewListViewItem("ResItem");
            var resItem = item.GetComponent<ResItem>();
            resItem.Init(route, OnResItemSelect);
            resItem.SetStateOn(m_activePacket.guid == route.guid);
            return item;
        }

        private void OnResItemSelect(Route route)
        {
            this.ShowState("show detail :" + route.guid, Color.green);
            m_activePacket = route;
            EditPanel.gameObject.SetActive(false);
            NameInfo.text = route.name;
            DesInfo.text = route.description;
            m_assetPathDic.TryGetValue(route.guid, out string sourcePath);
            var pathExists = !string.IsNullOrEmpty(sourcePath);
            filePathInputField.gameObject.SetActive(!pathExists);
            filePathApplyBtn.gameObject.SetActive(!pathExists);
            filePathText.gameObject.SetActive(pathExists);
            if (pathExists)
            {
                filePathText.text = sourcePath;
                var files = System.IO.Directory.GetFiles(sourcePath);
                ShowFiles(files);
            }
            else
            {
                ShowFiles(new string[] { });
            }
        }

        protected void ShowFiles(string[] files)
        {
            files = files.Where(x => !x.EndsWith(".geta")).ToArray();
            fileCountText.text = files.Length.ToString();
            ActiveFileListContent.ClearOldItems();
            for (int i = 0; i < files.Length; i++)
            {
                var item = ActiveFileListContent.AddItem();
                var fileItem = item.GetComponent<FileItem>();
                fileItem.ShowFile(files[i]);
                fileItem.onAsIconBtnClick = SetAsIcon;
            }
        }

        protected string LayerToNames(int layer)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < ResLayerName.MAX_LAYER_COUNT; i++)
            {
                if (ResLayerName.MaskContains(layer, i))
                {
                    var layerName = ResLayerName.layerNames[i];
                    sb.Append(layerName + "|");
                }
            }
            var names = sb.ToString();
            if (names.Length > 1)
            {
                names = names.Substring(0, names.Length - 1);
            }
            return names;
        }

        protected void OnSelectLayerIds(int[] ids)
        {
            if (ids != null)
            {
                int layer = 0;
                for (int i = 0; i < ids.Length; i++)
                {
                    layer |= ResLayerName.IDToMask(ids[i]);
                }
                if (m_activePacket != null)
                {
                    m_activePacket.source = layer;
                    TypeInfoText.text = LayerToNames(m_activePacket.source);
                }
                RefreshResList();
            }
        }

        protected void ShowEditPanel()
        {
            if (m_activePacket != null)
            {
                EditPanel.gameObject.SetActive(true);
                DescInput.text = m_activePacket.description;
                NameInput.text = m_activePacket.name;
                TagsInput.text = m_activePacket.flag;
            }
        }

        public byte[] LoadShortCart(byte[] bytes)
        {
            var scale = bytes.Length / 2048f;
            byte[] recordBytes = null;
            if (scale >= 1)
                recordBytes = TextureTool.ScaleTextureToTargetLength(bytes, 80);
            else
                recordBytes = bytes;

            return recordBytes;
        }



    }
}